const dotenv = require('dotenv');
const result = dotenv.config();
if (result.error) {
    throw result.error;
}
const retry = require('bluebird-retry');
const retryPromise = require('bluebird');
const config = require('./config');
const MetamonApi = require('./metamon_api');
const Web3 = require('web3');

let wait = ms => new Promise(resolve => setTimeout(resolve, ms));


async function run(config) {
    console.log("=====================程序开始执行==========================");
    try {
        let metamonApi = new MetamonApi(config.address, config.chain, config.privateKey);
        let accessToken = await metamonApi.login();
        metamonApi.setAccessToken(accessToken);

        ///查询背包
        let nfts = await metamonApi.checkBag();
        let chips;
        for (let i=0; i<nfts.length; i++) {
            let item = nfts[i];
            if (item.bpType == 1) {
                chips = item;
                break;
            }
        }
        if (!chips) {
            console.log("您的账号没有足够蛋碎片可合成！");
            return;
        } 
        let n = parseInt(chips.bpNum / 1000);
        console.log("拥有蛋碎片："+chips.bpNum+", 可合成"+n+"个蛋");
        
        if(chips && chips.bpNum > 1000) {
            let successCount = 0;
            let failCount = 0;
            
            for(let j=0; j<1; j++) {
                try {
                    let result = await metamonApi.mintEgg();
                    let data = result.data;
                    console.log(""+(n)+"个蛋合成成功");
                    successCount++;
                    
                } catch(e) {
                    console.log(""+(n)+"个蛋合成失败: " + e);
                    failCount++;
                }
                await wait(500);
            }
            console.log("合蛋结束，累积成功"+successCount+"次，失败"+failCount+"次");

        } else {
            console.log("您的账号没有足够蛋碎片可合成！");
        }
    } catch (e) {

    }

}


run(config);